import os
import sys
import tkinter as tk
from tkinter import scrolledtext
from pathlib import Path
from gui import create_main_gui, read_verification_code, input_verification_code
from myCryption import validate_license_code
from datetime import datetime


class Logger:
    def __init__(self, log_file):
        # self.text_area = scrolledtext.ScrolledText(root, wrap=tk.WORD, height=20, width=80)
        # self.text_area.pack(padx=10, pady=10)
        self.log_file = log_file

    # def log(self, message):
    #     self.text_area.insert(tk.END, message + "\n")
    #     self.text_area.yview(tk.END)
    def log(self, message):
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        formatted_message = f"{timestamp} - {message}"
        with open(self.log_file, 'a', encoding='utf-8') as f:
            f.write(formatted_message + "\n")


def get_file_path(filename):
    if getattr(sys, 'frozen', False):
        # If running in a bundle (frozen), use the directory where the executable is located
        base_path = Path(sys.executable).parent
    else:
        # If running in a normal Python environment, use the script's directory
        base_path = Path(__file__).parent
    return base_path / filename


def main():
    # 窗口输出 已注释
    # root = tk.Tk()
    # root.title("程序日志")

    # logger = Logger(root)
    log_file = get_file_path('application_log.txt')
    logger = Logger(log_file)
    # 获取文件路径
    file_name = get_file_path('../verification_code.txt')

    logger.log(f"文件路径为: {file_name}")

    # 检查文件是否存在，如果不存在则提示用户
    if not file_name.exists():
        logger.log("未找到校验码文件。")
        logger.log("请提供校验码。")
        if input_verification_code(file_name):
            logger.log("校验码已保存。")
            create_main_gui()
        else:
            logger.log("校验不通过。")
            root.mainloop()
            return

    verification_code = read_verification_code(file_name)

    if verification_code:
        logger.log(f"已找到校验码文件，校验码为: {verification_code}")
        ver_coding = validate_license_code(verification_code)
        if ver_coding:
            logger.log("校验码有效。")
            create_main_gui()
        else:
            logger.log("校验码无效。")
            logger.log("请重新输入校验码。")
            if input_verification_code(file_name):
                logger.log("校验码已保存。")
                create_main_gui()
            else:
                logger.log("校验不通过。")
    else:
        logger.log("未找到校验码文件。")
        logger.log("请输入校验码。")
        if input_verification_code(file_name):
            logger.log("校验码已保存。")
            create_main_gui()
        else:
            logger.log("校验不通过。")

    # root.mainloop()


if __name__ == "__main__":
    main()